package com.ricohgag.controller.admin;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ricohgag.entity.AdminUser;
import com.ricohgag.service.AdminUserService;
import com.ricohgag.util.Msg;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 肖晖
 * @since 2018-08-25
 */
@Controller
@RequestMapping("/admin")
public class AdminUserController {
    @Autowired
    private AdminUserService adminUserService;

    /**
     * 进入后台登录页面
     * @param request
     * @param username
     * @return
     * @throws Exception
     */
    @RequestMapping("/toLogin")
    public String toAdminLogin( HttpServletRequest request, String username) throws Exception{

        return "common/public/index";
    }

    /**
     * 进入首页
     * @param request
     * @return
     */
    @RequestMapping(value = "/toIndex")
    public String Index( HttpServletRequest request){
        return "admin/index/index";
    }

    @RequestMapping(value = "/work/index")
    public String toWorkIndex(){
        return "admin/work/index";
    }

    @RequestMapping("/adminUser/toIndex")
    public String toIndex(){
        return "/admin/adminUser/toIndex";
    }

    @RequestMapping("/adminUser/exit")
    public String toExit(HttpServletRequest request){
        request.getSession().removeAttribute("adminUserSession");
        return "redirect:/admin/toLogin";
    }


    /**
     * 进行账号密码验证，成功则进入后台首页
     * @param username
     * @param password
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/loginAdmin")
    @ResponseBody
    public Msg loginAdmin(String code, String username, String password, HttpServletRequest request) throws Exception{
        Msg msg = new Msg();
        //验证验证码
        System.err.println("code: "+code);
        HttpSession session = request.getSession();
        if(!code.equalsIgnoreCase(session.getAttribute("codeStr").toString())){
            msg.setStatus(0);
            msg.setMsg("验证码输入错误");
            return msg;
        }

        AdminUser adminUser = adminUserService.checkAdminUser(username, password);
        //当前用户
        Subject currentUser= SecurityUtils.getSubject();
        //验证信息
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        //登录
        try {
            currentUser.login(usernamePasswordToken);
            //表示是否认证成功！
            if(currentUser.isAuthenticated()) {
                msg.setStatus(1);
                msg.setMsg("登录成功！");
            }else {
                msg.setStatus(0);
                msg.setMsg("用户名或密码不正确");
            }
        }catch (UnknownAccountException e) {
            msg.setStatus(0);
            msg.setMsg("用户名或密码不正确");
        }catch (LockedAccountException e) {
            msg.setStatus(0);
            msg.setMsg("当前用户已经被禁止！");
        }

        return msg;

    }

    /****************************************************************/
    /****************下面为系统用户的业务代码************************/
    /****************************************************************/

    /**
     *
     * @param username
     * @param startDate
     * @param endDate
     * @param current
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/adminUser/index")
    public ModelAndView toAdminUserIndex(String username, String startDate, String endDate, Integer current, HttpServletRequest request) throws Exception{
        System.err.println("name:: "+username);
        ModelAndView mav = new ModelAndView("/admin/adminUser/index");
        String url = request.getContextPath()+"/admin/adminUser/index";

        if(current == null){
            current = 1;
        }
        Page<AdminUser> page = new Page<>(current, 10);

        IPage<AdminUser> adminUserIPage = adminUserService.selectAdminUserPage(username, page, startDate, endDate);
        mav.addObject("name",username);
        mav.addObject("Pager", adminUserIPage);
        mav.addObject("pages", adminUserIPage.getPages());
        mav.addObject("url",url);
        return mav;
    }

    @RequestMapping("/adminUser/toAdd")
    public ModelAndView toAdd(Integer id) throws Exception{
        ModelAndView mav = new ModelAndView("admin/adminUser/saveOrUpdate");
        if(!"0".equals(id)){
            AdminUser adminUser = adminUserService.selectAdminUserOne(id);
            mav.addObject("adminUser", adminUser);
        }
        return mav;
    }

    @RequestMapping("/adminUser/saveOrUpdate")
    public String saveOrUpdate(AdminUser adminUser, MultipartFile imgFile, HttpServletRequest request) throws Exception{

        //判断id为空则增加，反之则更改
        if(adminUser.getId() == null){
            adminUserService.insertAdminUser(adminUser);
        } else {
            adminUserService.updateAdminUser(adminUser);
        }

        return "/common/public/reload";
    }

    @RequestMapping(value = "/adminUser/delete", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String deleteShopAd(Integer id, HttpServletResponse response) throws Exception{
        Map<String, String> map = new HashMap<>();
        int count = adminUserService.deleteAdminUser(id);

        if(count > 0){
            map.put("msg", "删除成功");
        } else {
            map.put("msg", "删除失败");
        }
        response.setCharacterEncoding("utf-8");
        String jsonStr = JSON.toJSONString(map);
        return jsonStr;
    }

}

